﻿#region "Copyright (C) Lenny Granovsky. 2005-2013"
//This program is free software distribute under the terms of the GNU General Public License as published by
//the Free Software Foundation. Please read AssemblyInfo.cs file for more information.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Web.Enhancements.Rest
{
    [Serializable()]
    internal class ParameterJSFormatter : ParameterFormatter
    {
        public ParameterJSFormatter()
        {
        }

        public static ParameterJSFormatter CreateInstance()
        {
            ParameterJSFormatter formatter = (ParameterJSFormatter)ParameterFormatter.CreateInstance(typeof(ParameterJSFormatter), null);
            return formatter;
        }

        public override void Initialize(System.Reflection.MethodInfo initializer)
        {
            this.methodInfo = initializer;
        }

        public override string FormatParameters(object[] parameters)
        {
            StringBuilder sbr = new StringBuilder();
            Type type = null;
            foreach (object item in parameters)
            {
                type = item.GetType();
                if (type.IsEnum)
                    sbr.AppendFormat("{0},", Convert.ChangeType(item, type.GetEnumUnderlyingType()).ToString());
                else if (type.IsPrimitive)
                {
                    switch (type.Name)
                    {
                        case "Char":
                        case "DateTime":
                        case "DateSpan":
                            sbr.AppendFormat("'{0}',", item.ToString());
                            break;
                        default:
                            sbr.AppendFormat("{0},", item.ToString());
                            break;
                    }
                }
                else
                    sbr.AppendFormat("'{0}',", item.ToString());
            }
            if (sbr.Length > 0)
            {
                if (sbr[sbr.Length - 1] == ',')
                    sbr = sbr.Remove(sbr.Length - 1, 1);
            }
            return sbr.ToString();
        }
    }
}
